<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- 租户 -->
      <el-form-item label="租户" prop="rechargeTenantId">
        <el-select
          v-model="queryParams.rechargeTenantId"
          placeholder="请选择租户"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="opt in tenantOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="名单等级" prop="listLevel">
        <el-select
          v-model="queryParams.listLevel"
          placeholder="请选择名单等级"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.LIST_LEVEL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="营销工具" prop="marketingTools">
        <el-select
          v-model="queryParams.marketingTools"
          placeholder="请选择营销工具"
          clearable
          filterable
          multiple
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.MARKETING_TOOL)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="拉取条数" prop="pullCount">
        <el-input
          v-model="queryParams.pullCount"
          placeholder="请输入拉取条数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="是否启用" prop="enabled">
        <el-select
          v-model="queryParams.enabled"
          placeholder="请选择是否启用"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['vos:push-list-config:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:push-list-config:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['vos:push-list-config:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="租户" align="center" prop="rechargeTenantId" min-width="120">
        <template #default="{ row }">
          {{ tenantNameMap[row.rechargeTenantId] ?? row.rechargeTenantId ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column label="名单等级" align="center" prop="listLevel">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.LIST_LEVEL" :value="scope.row.listLevel" />
        </template>
      </el-table-column>
      <el-table-column label="营销工具" align="center" prop="marketingTools" min-width="160">
        <template #default="scope">
          <span>{{ getMarketingToolLabels(scope.row.marketingTools) }}</span>
        </template>
      </el-table-column>
      <!-- 已按要求移除：通道 channel 列 -->
      <el-table-column label="拉取条数" align="center" prop="pullCount" />
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.enabled" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['vos:push-list-config:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['vos:push-list-config:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PushListConfigForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { PushListConfigApi, PushListConfig } from '@/api/vos/pushlistconfig'
import PushListConfigForm from './PushListConfigForm.vue'
import * as TenantApi from '@/api/system/tenant'

/** 名单推送配置 列表 */
defineOptions({ name: 'PushListConfig' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<PushListConfig[]>([])
const total = ref(0)
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  rechargeTenantId: undefined,
  listLevel: undefined,
  pullCount: undefined,
  enabled: undefined,
  createTime: [],
  // 仍按你的原逻辑：后端接收逗号分隔的字符串
  marketingTools: ''
})
const queryFormRef = ref()
const exportLoading = ref(false)

/** 租户下拉 */
type TenantOption = { value: number; label: string }
const tenantOptions = ref<TenantOption[]>([])
const tenantNameMap = reactive<Record<number, string>>({})
const loadTenants = async () => {
  const res = await TenantApi.getTenantList()
  const arr = Array.isArray(res) ? res : (res?.list ?? [])
  tenantOptions.value = arr.map((it: any) => {
    const id = Number(it.id)
    const label = it.name || `租户#${id}`
    tenantNameMap[id] = label
    return { value: id, label }
  })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PushListConfigApi.getPushListConfigPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await PushListConfigApi.deletePushListConfig(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 批量删除 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: PushListConfig[]) => {
  checkedIds.value = records.map((item) => item.id)
}
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await PushListConfigApi.deletePushListConfigList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await PushListConfigApi.exportPushListConfig(queryParams)
    download.excel(data, '名单推送配置.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取营销工具的标签 */
const getMarketingToolLabels = (tools: string) => {
  if (!tools) return '-'
  const toolIds = tools.split(',')
  const labels = toolIds
    .map((id) => {
      const dict = getStrDictOptions(DICT_TYPE.MARKETING_TOOL).find((item) => item.value === id)
      return dict ? dict.label : id
    })
    .join(', ')
  return labels
}

/** 初始化 **/
onMounted(async () => {
  await loadTenants()
  await getList()
})
</script>
